package Algorithm.array;

import Algorithm.list.ListNode;

import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.PriorityQueue;

/**
 * @Desc:   合并区间
 * 给出一个区间的集合，请合并所有重叠的区间。
 *
 * 示例 1:
 *
 * 输入: [[1,3],[2,6],[8,10],[15,18]]
 * 输出: [[1,6],[8,10],[15,18]]
 * 解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
 * 示例 2:
 *
 * 输入: [[1,4],[4,5]]
 * 输出: [[1,5]]
 * 解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。
 * @author: cww
 * @DateTime: 2020/4/9 15:40
 */

public class Merge {
    public static void main(String[] args) {
        int[][] m = {
                {1,3},
                {2,6},
                {8,10},
                {15,18}};
        System.out.println(merge(m));
    }

    public static int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });
        LinkedList<int []> list = new LinkedList<>();
        for(int i = 0;i<intervals.length;i++){
            if(list.size()==0||list.getLast()[1]<intervals[i][0]){
                list.add(intervals[i]);
            }else{
                list.getLast()[1] = Math.max(list.getLast()[1],intervals[i][1]);
            }
        }
        int[][] result = new int[list.size()][2];
        int index = 0;
        while(!list.isEmpty()){
            result[index++] = list.pollFirst();
        }
        return result;
    }

    public ListNode mergeKLists(ListNode[] lists) {
        ListNode dummy = new ListNode(0);
        ListNode head = dummy;
        PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>((o1, o2) -> Integer.compare(o1.val,o2.val));
        for(ListNode node:lists){
            if(node!=null) queue.offer(node);
        }
        while(!queue.isEmpty()){
            ListNode next = queue.poll();
            head.next = next;
            head = head.next;
        }
        return dummy.next;
    }

}























